package com.yjf.ljr.activity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.TextView;
import android.widget.Toast;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.LoginActivity.AccountOverviewTask;
import com.yjf.ljr.application.MyApplication;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.EasyDataClass;
import com.yjf.ljr.dataclass.LoginDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AESUtil;
import com.yjf.ljr.util.Base64;
import com.yjf.ljr.util.LockPatternUtils;
import com.yjf.ljr.util.SPreferences;
import com.yjf.ljr.view.LockPatternView;
import com.yjf.ljr.view.LockPatternView.Cell;
import com.yjf.ljr.view.LockPatternView.DisplayMode;

public class LockPatternActivity extends IjActivity {
	@ID("user_info")
	private TextView userInfo;
	@ID("lock_pattern")
	private LockPatternView lockPattern;
	@ID("lock_pattern_tip")
	private TextView lockPatternTip;
	@ID("lock_pattern_login_tip")
	private TextView lockPatternLoginTip;

	@ID("lock_pattern_forget")
	private TextView lockPatternForget;

	@ID("lock_pattern_no_create")
	private TextView lockPatternNoCreate;

	public static boolean IS_SHOW = false;// 是否运行了
	public boolean isShowNonSetting = false;

	private LockPatternUtils lockPatternUtils;
	private TextView lockPatternTipTv;
	private Stage mUiStage = Stage.Introduction;// 默认手势状态
	private static int tryInputCount = 1;// 失败尝试次数

	private static int changeConfirmTryCount = 1;// 设置或修改时，确认密码尝试次数

	private MyApplication myApplication;
	
	public static final String FROM_LOCKPATTERN = "fromLockPattern";

	private static final int WRONG_PATTERN_CLEAR_TIMEOUT_MS = 2000;// 手势密码错误后等待重置时间
	private static final int FAILED_ATTEMPTS = 5;// 手势密码输入失败尝试总次数
	private boolean isSettingLockPattern = false;
	private final List<LockPatternView.Cell> mAnimatePattern = new ArrayList<LockPatternView.Cell>();// 手势示例
	protected List<LockPatternView.Cell> mChosenPattern = null;
	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			lockPattern.clearPattern();
		}
	};

	private Runnable reCreatePatternRunnable = new Runnable() {
		public void run() {
			lockPattern.clearPattern();
			updateStage(Stage.Introduction);
		}
	};

	private final int LOCK_TIME_TIMEOUT_MS = 30 * 60 * 5000;
	private final int LOCK_EVENT = 1;
	private final int WEB_LOGIN_REQUEST = 2;
	private final int WEB_LOGIN_FORGET_REQUEST = 3;
	private String lastUserName = "";

	@SuppressLint("HandlerLeak")
	private Handler lockingHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOCK_EVENT:
				mUiStage = Stage.CheckToConfirm;
				lockPattern.clearPattern();
				tryInputCount = 1;
				changeConfirmTryCount = 1;
				updateStage(mUiStage);
				break;
			default:
				break;
			}
		}

	};

	/**
	 * The pattern listener that responds according to a user choosing a new
	 * lock pattern.
	 */
	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

		public void onPatternStart() {
			lockPattern.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			lockPattern.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<LockPatternView.Cell> pattern) {
			if (mUiStage == Stage.NeedToConfirm /*
												 * || mUiStage ==
												 * Stage.ConfirmWrong
												 */) {
				if (mChosenPattern == null)
					throw new IllegalStateException("null chosen pattern in stage 'need to confirm");
				if (mChosenPattern.equals(pattern)) {
					updateStage(Stage.ChoiceConfirmed);
				} else {
					updateStage(Stage.ConfirmWrong);
				}
			} else if (mUiStage == Stage.Introduction || mUiStage == Stage.ChoiceTooShort) {
				if (pattern.size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
					updateStage(Stage.ChoiceTooShort);
				} else {
					mChosenPattern = new ArrayList<LockPatternView.Cell>(pattern);
					updateStage(Stage.NeedToConfirm);
				}
			} else if (mUiStage == Stage.CheckToConfirm || mUiStage == Stage.CheckConfirmWrong) {
				if (pattern == null)
					throw new IllegalStateException("null chosen pattern in stage 'need to confirm");
				if (lockPatternUtils.checkPattern(pattern)) {
					updateStage(Stage.CheckConfirmed);
				} else {
					updateStage(Stage.CheckConfirmWrong);
				}
			} else if (mUiStage == Stage.Change || mUiStage == Stage.ChangeWrong) {
				if (lockPatternUtils.checkPattern(pattern)) {
					updateStage(Stage.Introduction);
				} else {
					updateStage(Stage.ChangeWrong);
				}
			} else if (mUiStage == Stage.ConfirmWrong) {
				lockPattern.clearPattern();
				updateStage(Stage.Introduction);
			} else {
				throw new IllegalStateException("Unexpected stage " + mUiStage + " when " + "entering the pattern.");
			}
		}

		public void onPatternCellAdded(List<Cell> pattern) {

		}

		private void patternInProgress() {
			lockPatternTipTv.setText(R.string.lockpattern_recording_inprogress);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lock_pattern);
		setVerify(false);
		myApplication = (MyApplication) getApplication();
		initControl();
		IS_SHOW = true;
		tryInputCount = 1;
		changeConfirmTryCount = 1;
	}

	private void initControl() {
		lockPatternUtils = new LockPatternUtils(this);
		mAnimatePattern.add(LockPatternView.Cell.of(0, 0));
		mAnimatePattern.add(LockPatternView.Cell.of(0, 1));
		mAnimatePattern.add(LockPatternView.Cell.of(1, 1));
		mAnimatePattern.add(LockPatternView.Cell.of(2, 1));
		initLockStateAndTipView();
		lockPattern.setOnPatternListener(mChooseNewLockPatternListener);
		lockPattern.setTactileFeedbackEnabled(lockPatternUtils.isTactileFeedbackEnabled());

		lockPatternLoginTip.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				lastUserName = "";
				Intent intent = new Intent();
				// intent.setClass(LockPatternActivity.this,
				// WvLoginActivity.class);
				// intent.putExtra("advUrl", CommonData.LOGIN_URL);
				// intent.putExtra("advTitle", "登录");
				// intent.putExtra("registration", "注册");
				intent.setClass(LockPatternActivity.this, LoginActivity.class);
				startActivityForResult(intent, WEB_LOGIN_REQUEST);
			}
		});

		updateStage(mUiStage);
	}

	private void initLockStateAndTipView() {
		isSettingLockPattern = false;
		Intent intent = getIntent();
		boolean isChangeLockPattern = false;
		isShowNonSetting = false;
		if (intent != null) {
			isChangeLockPattern = intent.getBooleanExtra(LockPatternSettingActivity.IS_CHANGE_LOCK_PATTERN, false);
			isShowNonSetting = intent.getBooleanExtra(LoginActivity/* WvLoginActivity */.FIRST_LOGIN, false);
		}
		boolean lockVirgin = lockPatternUtils.isPatternEverChosen();
		if (lockVirgin) {
			// 修改密码
			if (isChangeLockPattern) {
				mUiStage = Stage.Change;
				isSettingLockPattern = true;
				lockPatternTipTv = userInfo;
				lockPatternLoginTip.setVisibility(View.INVISIBLE);
				lockPatternTip.setVisibility(View.GONE);
				lockPatternForget.setVisibility(View.GONE);
				lockPatternNoCreate.setVisibility(View.INVISIBLE);
			} else {
				mUiStage = Stage.CheckToConfirm;
				lockPatternTipTv = lockPatternTip;
				lockPatternLoginTip.setVisibility(View.VISIBLE);
				lockPatternForget.setVisibility(View.VISIBLE);
				lockPatternNoCreate.setVisibility(View.INVISIBLE);
				lockPatternForget.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						forgetLockPattern();
					}
				});
				String user = TextUtils.isEmpty(CommonData.USER_NAME) ? "" : (CommonData.USER_NAME + ",");
				userInfo.setText(getString(R.string.lock_pattern_user_info, user));
			}
		} else {
			// 新建密码
			mUiStage = Stage.Introduction;
			isSettingLockPattern = true;
			lockPatternLoginTip.setVisibility(View.INVISIBLE);
			lockPatternForget.setVisibility(View.INVISIBLE);
			lockPatternNoCreate.setVisibility(View.VISIBLE);
			lockPatternTipTv = userInfo;
			lockPatternTip.setVisibility(View.GONE);
			if (isShowNonSetting) {
				lockPatternNoCreate.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						SPreferences.saveData(LockPatternActivity.this, false, CommonData.USER_NAME
								+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
						// 关闭自动登陆
						myApplication.stopAutoLogin();
						Intent lockPatternintent = new Intent();
						lockPatternintent.putExtra(FROM_LOCKPATTERN, true);
						setResult(RESULT_OK,lockPatternintent);
						finish();
					}
				});
			} else {
				lockPatternNoCreate.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						finish();
					}
				});
			}
		}
	}

	/**
	 * Updates the messages and buttons appropriate to what stage the user is at
	 * in choosing a view. This doesn't handle clearing out the pattern; the
	 * pattern is expected to be in the right state.
	 * 
	 * @param stage
	 */
	protected void updateStage(Stage stage) {

		mUiStage = stage;

		// header text, footer text, visibility and
		// enabled state all known from the stage
		if (stage == Stage.ChoiceTooShort) {
			lockPatternTipTv.setText(getResources().getString(stage.headerMessage,
					LockPatternUtils.MIN_LOCK_PATTERN_SIZE));
		} else if (stage == Stage.ChangeWrong) {
			lockPatternTipTv.setText(getResources().getString(stage.headerMessage, FAILED_ATTEMPTS - tryInputCount));
		} /*
		 * else if (stage == Stage.ConfirmWrong) { lockPatternTipTv.setText(
		 * getResources().getString(
		 * R.string.lockpattern_change_confirm_error_timeslockpattern_change_error
		 * , FAILED_ATTEMPTS-changeConfirmTryCount)); }
		 */else if (stage == Stage.CheckConfirmWrong) {
			lockPatternTipTv.setText(getResources().getString(R.string.lockpattern_change_error,
					FAILED_ATTEMPTS - tryInputCount));
		} else {
			lockPatternTipTv.setText(stage.headerMessage);
		}

		// same for whether the patten is enabled
		if (stage.patternEnabled) {
			lockPattern.enableInput();
		} else {
			lockPattern.disableInput();
		}

		// the rest of the stuff varies enough that it is easier just to handle
		// on a case by case basis.
		lockPattern.setDisplayMode(DisplayMode.Correct);

		switch (mUiStage) {
		case Introduction:
			lockPattern.clearPattern();
			break;
		case HelpScreen:
			lockPattern.setPattern(DisplayMode.Animate, mAnimatePattern);
			break;
		case ChoiceTooShort:
			lockPattern.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case FirstChoiceValid:
			break;
		case NeedToConfirm:
			lockPattern.clearPattern();
			break;
		// 设置密码时，确认密码错误
		case ConfirmWrong:
			lockPattern.setDisplayMode(DisplayMode.Wrong);
			// postClearPatternRunnable();
			// if(changeConfirmTryCount < FAILED_ATTEMPTS) {
			// changeConfirmTryCount++;
			// } else {
			// lockPattern.disableInput();
			// lockPatternTipTv.setText(R.string.lockpattern_set_failed);
			// showToast(getString(R.string.lockpattern_set_failed));
			// setResult(RESULT_CANCELED);
			// finish();
			// }
			postRecreatePatternRunnable();
			break;
		// 设置手势密码成功
		case ChoiceConfirmed:
			saveChosenPatternAndFinish();
			// 第一次登陆，密码设置成功后默认开启手势密码功能,同时开启自动登陆功能
			if (isShowNonSetting) {
				SPreferences.saveData(LockPatternActivity.this, true, CommonData.USER_NAME
						+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
				// 开启自动登陆
				myApplication.startAutoLogin();
			}
			showToast(getString(R.string.lockpattern_set_success));
			Intent lockPatternintent = new Intent();
			lockPatternintent.putExtra(FROM_LOCKPATTERN, true);
			setResult(RESULT_OK,lockPatternintent);
			finish();
			break;
		case CheckConfirmed:
			// finish();
			// add auto login
			String userName = SPreferences.getUserName(this);
			String pwd = SPreferences.getPassword(this);
			if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(pwd)) {
				// new
				// LoginTask(userName,Base64.encode(pwd.getBytes())).execute();
				new LoginThread(userName, AESUtil.encode(pwd)).start();
			}
			Intent intent = new Intent();
			intent.putExtra("unlock", true);
			setResult(RESULT_CANCELED, intent);
			finish();
			break;
		// 手势密码界面，用于屏保作用
		case CheckConfirmWrong:
			lockPattern.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			if (tryInputCount < FAILED_ATTEMPTS) {
				tryInputCount++;
			} else {
				// 解锁失败
				lockPattern.disableInput();
				lockPatternTipTv.setText(R.string.lockpattern_unlock_failed);
				showToast(getString(R.string.lockpattern_unlock_failed_tip));
				lockingHandler.removeMessages(LOCK_EVENT);
				lockingHandler.sendEmptyMessageDelayed(LOCK_EVENT, LOCK_TIME_TIMEOUT_MS);
			}
			break;
		case Change:
			lockPattern.clearPattern();
			break;
		case ChangeWrong:
			lockPattern.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			if (tryInputCount < FAILED_ATTEMPTS) {
				tryInputCount++;
			} else {
				lockPattern.disableInput();
				lockPatternTipTv.setText(R.string.lockpattern_change_failed);
				showToast(getString(R.string.lockpattern_change_failed));
				finish();
			}
			break;
		default:
			break;
		}
	}

	// clear the wrong pattern unless they have started a new one
	// already
	private void postClearPatternRunnable() {
		lockPattern.removeCallbacks(mClearPatternRunnable);
		lockPattern.postDelayed(mClearPatternRunnable, WRONG_PATTERN_CLEAR_TIMEOUT_MS);
	}

	private void postRecreatePatternRunnable() {
		lockPattern.removeCallbacks(reCreatePatternRunnable);
		lockPattern.postDelayed(reCreatePatternRunnable, WRONG_PATTERN_CLEAR_TIMEOUT_MS);
	}

	private void saveChosenPatternAndFinish() {
		final boolean lockVirgin = !lockPatternUtils.isPatternEverChosen();

		lockPatternUtils.saveLockPattern(mChosenPattern);
		lockPatternUtils.setLockPatternEnabled(true);

		if (lockVirgin) {
			lockPatternUtils.setVisiblePatternEnabled(true);
			lockPatternUtils.setTactileFeedbackEnabled(false);
		}
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return false;
	}

	@Override
	public void onBackPressed() {
		if (isSettingLockPattern) {
			super.onBackPressed();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		IS_SHOW = false;
		lockingHandler.removeMessages(LOCK_EVENT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			if (requestCode == WEB_LOGIN_FORGET_REQUEST) {
				if (!TextUtils.isEmpty(lastUserName) && lastUserName.endsWith(CommonData.USER_NAME)) {
					// 清除以前的密码并设置新密码
					lockPatternUtils.deleteLockPattern();
					tryInputCount = 1;
					changeConfirmTryCount = 1;
					isShowNonSetting = true;
					mUiStage = Stage.Introduction;
					isSettingLockPattern = true;
					lockPatternLoginTip.setVisibility(View.INVISIBLE);
					lockPatternTip.setVisibility(View.GONE);
					lockPatternForget.setVisibility(View.INVISIBLE);
					lockPatternNoCreate.setVisibility(View.VISIBLE);
					lockPatternTipTv = userInfo;
					lockPatternNoCreate.setText("跳过，暂不设置");
					lockPatternNoCreate.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							SPreferences.saveData(LockPatternActivity.this, false, CommonData.USER_NAME
									+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
							// 关闭自动登陆
							myApplication.stopAutoLogin();
							Intent lockPatternintent = new Intent();
							lockPatternintent.putExtra(FROM_LOCKPATTERN, true);
							setResult(RESULT_OK,lockPatternintent);
							finish();
						}
					});
					updateStage(mUiStage);
				} else {
					// 登录成功，刷新界面
					Intent lockPatternintent = new Intent();
					lockPatternintent.putExtra(FROM_LOCKPATTERN, true);
					setResult(RESULT_OK,lockPatternintent);
					finish();
				}
			} else if (requestCode == WEB_LOGIN_REQUEST) {
				// 登录成功，刷新界面
				Intent lockPatternintent = new Intent();
				lockPatternintent.putExtra(FROM_LOCKPATTERN, true);
				setResult(RESULT_OK,lockPatternintent);
				finish();
			}
		}
	}

	private void forgetLockPattern() {
		new AlertDialog.Builder(this).setTitle("提示").setIcon(R.drawable.icon_exit)
				.setMessage("\n  忘记手势密码需要通过登录来重新设置。\n").setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						lastUserName = CommonData.USER_NAME;
						CommonData.SESSIONID = "";
						// 退出登陆，需将用户名清空
						CommonData.IS_LOGIN = false;
						MyAccountActivity.gIsLoginServer = false;

						// CommonData.USER_NAME = "";
						// 关闭自动登陆
						myApplication.stopAutoLogin();
						SPreferences.clearPassword(LockPatternActivity.this);

						// CookieManager cookieManager =
						// CookieManager.getInstance();
						// cookieManager.removeSessionCookie();
						// CookieSyncManager.getInstance().sync();

						Intent intent = new Intent();
						// intent.setClass(LockPatternActivity.this,
						// WvLoginActivity.class);
						// intent.putExtra("advUrl", CommonData.LOGIN_URL);
						// intent.putExtra("advTitle", "登录");
						// intent.putExtra("registration", "注册");
						intent.setClass(LockPatternActivity.this, LoginActivity.class);
						startActivityForResult(intent, WEB_LOGIN_FORGET_REQUEST);
					}
				}).setNegativeButton("取消", null).show();
	}

	/**
	 * Keep track internally of where the user is in choosing a pattern.
	 */
	protected enum Stage {
		Introduction(R.string.lockpattern_changed, true), HelpScreen(R.string.lockpattern_settings_help_how_to_record,
				false), ChoiceTooShort(R.string.lockpattern_recording_incorrect_too_short, true), FirstChoiceValid(
				R.string.lockpattern_pattern_entered_header, false), NeedToConfirm(
				R.string.lockpattern_need_to_confirm, true), ConfirmWrong(R.string.lockpattern_change_confirm_error,
				false), ChoiceConfirmed(R.string.lockpattern_pattern_confirmed_header, false), CheckConfirmWrong(
				R.string.lockpattern_need_to_unlock_wrong, true), CheckToConfirm(R.string.lockpattern_input_pattern,
				true), CheckConfirmed(R.string.lockpattern_unlock_success, true), Change(R.string.lockpattern_change,
				true), ChangeWrong(R.string.lockpattern_change_error, true);

		/**
		 * @param headerMessage
		 *            The message displayed at the top.
		 * @param leftMode
		 *            The mode of the left button.
		 * @param rightMode
		 *            The mode of the right button.
		 * @param footerMessage
		 *            The footer message.
		 * @param patternEnabled
		 *            Whether the pattern widget is enabled.
		 */
		Stage(int headerMessage, boolean patternEnabled) {
			this.headerMessage = headerMessage;
			this.patternEnabled = patternEnabled;
		}

		final int headerMessage;
		final boolean patternEnabled;
	}

	class LoginTask extends AsyncTask<Void, Void, Void> {

		private String mFailStr;

		private String mUserName;
		private String mPassWord;
		private LoginDataClass dc = new LoginDataClass();

		public LoginTask(String username, String password) {
			super();
			this.mUserName = username;
			this.mPassWord = password;
		}

		@Override
		protected void onPreExecute() {
			// showProgressDialog();
		}

		@Override
		protected Void doInBackground(Void... param) {
			// TODO Auto-generated method stub
			boolean isConnected = false;
			RequestObject connectRequestobj = new RequestObject();
			connectRequestobj.method = "keepConnecting";
			String requestUrl = RequestBuilder.build(connectRequestobj);
			EasyDataClass dc = new EasyDataClass();
			try {
				IjConnect.doRequest(requestUrl, dc);
				if (!TextUtils.isEmpty(dc.code) && dc.code.equals(CommonData.RESULT_SUCCESS)) {
					isConnected = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!isConnected) {
				RequestObject requestObject = new RequestObject();
				requestObject.method = "login";
				requestObject.map.put("userName", mUserName);
				requestObject.map.put("passWord", mPassWord);

				String requrestUrl = RequestBuilder.build(requestObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);
					if (dc.code == null) {
						mFailStr = getResources().getString(R.string.loaddata_exception);
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						mFailStr = dc.msg;
					}
				} catch (Exception e) {
					// TODO: handle exception
					mFailStr = getResources().getString(R.string.loaddata_exception);
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// dismissProgressDialog();
			if (!TextUtils.isEmpty(mFailStr)) {
				finish();
				// showToast("登录失败！"/*mFailStr*/);
				// mUiStage = Stage.CheckToConfirm;
				// lockPattern.clearPattern();
				// tryInputCount = 1;
				// changeConfirmTryCount = 1;
				// updateStage(mUiStage);
			} else {
				CommonData.FLAG_LOGIN_SERVER = true;
				CommonData.IS_LOGIN = true;
				MyAccountActivity.gIsLoginServer = true;
				// showToast(getString(R.string.lockpattern_unlock_success));
				Intent lockPatternintent = new Intent();
				lockPatternintent.putExtra(FROM_LOCKPATTERN, true);
				setResult(RESULT_OK,lockPatternintent);
				finish();
			}
		}

	}

	class LoginThread extends Thread {
		public String username;
		public String password;

		public LoginThread(String username, String password) {
			this.username = username;
			this.password = password;
		}

		@Override
		public void run() {
			boolean isConnected = false;
			RequestObject connectRequestobj = new RequestObject();
			connectRequestobj.method = "keepConnecting";
			String requestUrl = RequestBuilder.build(connectRequestobj);
			EasyDataClass dc = new EasyDataClass();
			try {
				IjConnect.doRequest(requestUrl, dc);
				if (!TextUtils.isEmpty(dc.code) && dc.code.equals(CommonData.RESULT_SUCCESS)) {
					isConnected = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!isConnected) {
				RequestObject requestObject = new RequestObject();
				requestObject.method = "login";
				requestObject.map.put("userName", username);
				String pwdStr = URLEncoder.encode(password);
				requestObject.map.put("passWord", pwdStr);
				String requrestUrl = RequestBuilder.build(requestObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}
